#include "serialport.h"
#include "cstring"
#include <iostream>
using namespace std;

SerialPort::SerialPort(QObject *parent) : QObject(parent)
{
    mode = 0;
//    my_thread = new QThread();

    port = new QSerialPort();
    init_port();
//    this->moveToThread(my_thread);
//    port->moveToThread(my_thread);
//    my_thread->start();//启动线程
//    connect(port, SIGNAL(readyRead()), this, SLOT(handle_data()));
    qDebug()<<"okkkkkkk";
    connect(port,&QSerialPort::readyRead,this,&SerialPort::handle_data);
//    if(my_thread -> isRunning())
//    {
//        qDebug()<<"okkkkkkk";
//    }
//    else
//    {
//        qDebug()<<"addddddd";
//    }
    qDebug()<<"addddddd";
}

SerialPort::~SerialPort()
{
    port->close();
    port->deleteLater();
    my_thread->quit();
    my_thread->wait();
    my_thread->deleteLater();
}

void SerialPort::init_port()
{
    port->setPortName("/dev/ttyACM0");                   //串口名 windows下写作COM1
    if(port -> isOpen())
    {
        port -> close();
    }
    if (port->open(QIODevice::ReadWrite))
    {
        qDebug() << "Port have been opened";
    }
    else
    {
        qDebug() << "open it failed";
    }
    port->setBaudRate(1000000);                           //波特率
    port->setDataBits(QSerialPort::Data8);             //数据位
    port->setStopBits(QSerialPort::OneStop);           //停止位
    port->setParity(QSerialPort::NoParity);            //奇偶校验
    port->setFlowControl(QSerialPort::NoFlowControl);  //流控制
    port->setReadBufferSize(40960);
//    connect(port, SIGNAL(readyRead()), this, SLOT(handle_data()));

    qDebug() << "port is open";
}

void SerialPort::handle_data()
{
    QByteArray data = port->readAll();
//    qDebug() << data;
//    qDebug() << QStringLiteral("data received(收到的数据):") << data;
//    qDebug() << "handing thread is:" << QThread::currentThreadId();
    struct MODE{
        char mode;
    }Mode;
    //qDebug() << "Run Here";
    memcpy(&Mode,data.data(),sizeof(MODE));
    qDebug() << Mode.mode ;

    if(Mode.mode == '0')
        mode = 0;
    if(Mode.mode == '1')
    {
        mode = 1;
        //qDebug() << "1" ;
    }

    if(mode != 0){
        write_data();
        qDebug() << "write_data";
      }
}

void SerialPort::write_data()
{
    char data[8];
    //NUC2STM.pitch = -30.0f;
    //NUC2STM.yaw = 0.1f;
    memcpy(data,&NUC2STM,8);
    qDebug() << data;
    if(port -> write(data,8) == 0)
        qDebug() << "2";
}
